package com.system.main.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.system.main.model.Info;
import com.system.main.model.Response;
import com.system.main.model.User;
import com.system.main.model.UserRequest;
import com.system.main.service.UserService;
import com.system.main.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

@CrossOrigin(origins = "*", maxAge=3600)
@Slf4j
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    /**登录验证**/
    @PostMapping("/check_user")
    @ResponseBody
    public Response userLogin(@RequestBody UserRequest userRequest, HttpServletResponse response) {
        User user = userService.checkUser(userRequest);
        Response backResponse = new Response();
        if (null != user){
            String jwt_token = JwtUtil.generateJwt(user);

            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.addHeader("Set-Cookie", "HttpOnly");

            backResponse = successResponse(backResponse);
            JSONObject userIdCookie = new JSONObject();
            userIdCookie.put("user_id", user.getId().toString());
            JSONObject jwtCookie = new JSONObject();
            jwtCookie.put("jwt_token", jwt_token);
            JSONArray data = new JSONArray();
            data.add(userIdCookie);
            data.add(jwtCookie);
            backResponse.setData(new Info("data", data));

            log.info("用户："+user.getName()+"登录");
        }else{
            backResponse = failResponse(backResponse, "账号或密码错误");
        }
        return backResponse;
    }

    @GetMapping("/testCheck")
    public User testCheck(@RequestParam String token) {
        User user = new User();
        user = JwtUtil.getUserInfoByJwt(token);
        return user;
    }

    private Response successResponse(Response response) {
        response.setCode(0);
        response.setMsg("success");
        return response;
    }

    private Response failResponse(Response response, String msg) {
        response.setCode(1);
        response.setMsg(msg);
        return response;
    }

}
